<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="清算日期">
        <el-date-picker
          v-model="daterangeSettlementDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="合约编码" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合约编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成交价格" prop="executionPrice">
        <el-input
          v-model="queryParams.executionPrice"
          placeholder="请输入成交价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成交数量" prop="executedQuantity">
        <el-input
          v-model="queryParams.executedQuantity"
          placeholder="请输入成交数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <div class="column-selector-wrapper">
        <span class="column-label"><i class="el-icon-setting"></i>列隐藏：</span>
        <div class="column-selector">
          <el-select
            v-model="selectedColumns"
            multiple
            collapse-tags
            placeholder="选择要隐藏的列"
            size="small"
            style="width: 240px;"
          >
            <el-option
              v-for="column in allColumns"
              :key="column.prop"
              :label="column.label"
              :value="column.prop"
            />
          </el-select>
        </div>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="tradeRecordList">
      <el-table-column
        label="清算日期"
        align="center"
        prop="settlementDate"
        width="120"
        sortable
        v-if="isColumnVisible('settlementDate')">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.settlementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="清算组编号"
        align="center"
        prop="clearGroupNumber"
        v-if="isColumnVisible('clearGroupNumber')"/>
      <el-table-column
        label="合约编码"
        align="center"
        prop="contractCode"
        width="120"
        v-if="isColumnVisible('contractCode')"/>
      <el-table-column
        label="合约简称"
        align="center"
        prop="contractAbbreviation"
        width="140"
        v-if="isColumnVisible('contractAbbreviation')"/>
      <el-table-column
        label="买卖方向"
        align="center"
        prop="tradeDirection"
        width="80"
        v-if="isColumnVisible('tradeDirection')">
        <template slot-scope="scope">
          {{ scope.row.tradeDirection === 0 ? '买入' : '卖出' }}
        </template>
      </el-table-column>
      <el-table-column
        label="开平"
        align="center"
        prop="positionAction"
        v-if="isColumnVisible('positionAction')">
        <template slot-scope="scope">
          {{ scope.row.positionAction === 0 ? '开仓' : '平仓' }}
        </template>
      </el-table-column>
      <el-table-column
        label="成交价格"
        align="center"
        prop="executionPrice"
        v-if="isColumnVisible('executionPrice')"/>
      <el-table-column
        label="成交数量"
        align="center"
        prop="executedQuantity"
        v-if="isColumnVisible('executedQuantity')"/>
      <el-table-column
        label="成交金额"
        align="center"
        prop="executedAmount"
        v-if="isColumnVisible('executedAmount')"/>
      <el-table-column
        label="委托价格"
        align="center"
        prop="orderPrice"
        v-if="isColumnVisible('orderPrice')"/>
      <el-table-column
        label="委托数量"
        align="center"
        prop="orderQuantity"
        v-if="isColumnVisible('orderQuantity')"/>
      <el-table-column
        label="类别"
        align="center"
        prop="optionType"
        v-if="isColumnVisible('optionType')">
        <template slot-scope="scope">
          {{ scope.row.optionType === 0 ? '认购' : '认沽' }}
        </template>
      </el-table-column>
      <el-table-column
        label="备兑"
        align="center"
        prop="covered"
        v-if="isColumnVisible('covered')">
        <template slot-scope="scope">
          {{ scope.row.covered === 0 ? '非备兑' : '备兑' }}
        </template>
      </el-table-column>
      <el-table-column
        label="委托号"
        align="center"
        prop="orderId"
        v-if="isColumnVisible('orderId')"/>
      <el-table-column
        label="委托时间"
        align="center"
        prop="orderTime"
        width="180"
        v-if="isColumnVisible('orderTime')">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="交易市场"
        align="center"
        prop="tradingMarket"
        width="120"
        v-if="isColumnVisible('tradingMarket')"/>
      <el-table-column
        label="合同编号"
        align="center"
        prop="contractNumber"
        width="120"
        v-if="isColumnVisible('contractNumber')"/>
      <el-table-column
        label="印花税率"
        align="center"
        prop="stampDutyRate"
        v-if="isColumnVisible('stampDutyRate')"/>
      <el-table-column
        label="经手费"
        align="center"
        prop="brokerageFee"
        v-if="isColumnVisible('brokerageFee')"/>
      <el-table-column
        label="证管费"
        align="center"
        prop="regulatoryFee"
        v-if="isColumnVisible('regulatoryFee')"/>
      <el-table-column
        label="清算费"
        align="center"
        prop="settlementFee"
        v-if="isColumnVisible('settlementFee')"/>
      <el-table-column
        label="过户费"
        align="center"
        prop="transferFee"
        v-if="isColumnVisible('transferFee')"/>
      <el-table-column
        label="交易过户费"
        align="center"
        prop="transactionTransferFee"
        width="100"
        v-if="isColumnVisible('transactionTransferFee')"/>
      <el-table-column
        label="行权过户费"
        align="center"
        prop="exerciseTransferFee"
        width="100"
        v-if="isColumnVisible('exerciseTransferFee')"/>
      <el-table-column
        label="交易规费"
        align="center"
        prop="transactionLevy"
        v-if="isColumnVisible('transactionLevy')"/>
      <el-table-column
        label="佣金"
        align="center"
        prop="commission"
        v-if="isColumnVisible('commission')"/>
      <el-table-column
        label="清算金额"
        align="center"
        prop="settlementAmount"
        v-if="isColumnVisible('settlementAmount')"/>
      <el-table-column
        label="利润分组"
        align="center"
        prop="profitGroup"
        v-if="isColumnVisible('profitGroup')"/>
      <el-table-column
        label="交割月"
        align="center"
        prop="deliveryMonth"
        v-if="isColumnVisible('deliveryMonth')"/>
      <el-table-column
        label="清算标识"
        align="center"
        prop="clearFlag"
        v-if="isColumnVisible('clearFlag')">
        <template slot-scope="scope">
          {{ scope.row.clearFlag === 0 ? '未清算' :
          scope.row.clearFlag === 1 ? '已清算' : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="杠杆数量"
        align="center"
        prop="leverageQuantity"
        v-if="isColumnVisible('leverageQuantity')"/>
      <el-table-column
        label="其他损益费"
        align="center"
        prop="otherPlFee"
        v-if="isColumnVisible('otherPlFee')"/>
      <el-table-column
        label="其他损益描述"
        align="center"
        prop="otherPlDescription"
        v-if="isColumnVisible('otherPlDescription')"/>
      <el-table-column
        label="备用金"
        align="center"
        prop="reserveFund"
        v-if="isColumnVisible('reserveFund')"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listTradeRecord, getTradeRecord, delTradeRecord, addTradeRecord, updateTradeRecord, assignClearGroup, clearGroupNumber} from "@/api/trade/tradeRecord"
import { getToken } from "@/utils/auth"

export default {
  name: "TradeRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成交记录表格数据
      tradeRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新时间时间范围
      daterangeSettlementDate: [],
      // 交易记录导入参数
      upload: {
        // 是否显示弹出层（交易记录导入）
        open: false,
        // 弹出层标题（交易记录导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的交易记录数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/trade/tradeRecord/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        settlementDate: null,
        contractCode: null,
        executionPrice: null,
        executedQuantity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractNumber: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
      },
      // 新增：列显示控制相关数据
      allColumns: [
        { prop: 'settlementDate', label: '清算日期' },
        { prop: 'clearGroupNumber', label: '清算组编号' },
        { prop: 'contractCode', label: '合约编码' },
        { prop: 'contractAbbreviation', label: '合约简称' },
        { prop: 'tradeDirection', label: '买卖方向' },
        { prop: 'positionAction', label: '开平' },
        { prop: 'executionPrice', label: '成交价格' },
        { prop: 'executedQuantity', label: '成交数量' },
        { prop: 'executedAmount', label: '成交金额' },
        { prop: 'orderPrice', label: '委托价格' },
        { prop: 'orderQuantity', label: '委托数量' },
        { prop: 'optionType', label: '类别' },
        { prop: 'covered', label: '备兑' },
        { prop: 'orderId', label: '委托号' },
        { prop: 'orderTime', label: '委托时间' },
        { prop: 'tradingMarket', label: '交易市场' },
        { prop: 'contractNumber', label: '合同编号' },
        { prop: 'stampDutyRate', label: '印花税率' },
        { prop: 'brokerageFee', label: '经手费' },
        { prop: 'regulatoryFee', label: '证管费' },
        { prop: 'settlementFee', label: '清算费' },
        { prop: 'transferFee', label: '过户费' },
        { prop: 'transactionTransferFee', label: '交易过户费' },
        { prop: 'exerciseTransferFee', label: '行权过户费' },
        { prop: 'transactionLevy', label: '交易规费' },
        { prop: 'commission', label: '佣金' },
        { prop: 'settlementAmount', label: '清算金额' },
        { prop: 'profitGroup', label: '利润分组' },
        { prop: 'deliveryMonth', label: '交割月' },
        { prop: 'clearFlag', label: '清算标识' },
        { prop: 'leverageQuantity', label: '杠杆数量' },
        { prop: 'otherPlFee', label: '其他损益费' },
        { prop: 'otherPlDescription', label: '其他损益描述' },
        { prop: 'reserveFund', label: '备用金' }
      ],
      selectedColumns: []
    }
  },
  created() {
    // 初始化选中所有列
    this.selectedColumns = this.allColumns.map(column => column.prop);
    this.getList();
  },
  methods: {
    /** 查询成交记录列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeSettlementDate && '' != this.daterangeSettlementDate) {
        this.queryParams.params["beginSettlementDate"] = this.daterangeSettlementDate[0]
        this.queryParams.params["endSettlementDate"] = this.daterangeSettlementDate[1]
      }
      listTradeRecord(this.queryParams).then(response => {
        this.tradeRecordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        settlementDate: null,
        contractCode: null,
        contractAbbreviation: null,
        tradeDirection: null,
        positionAction: null,
        executionPrice: null,
        executedQuantity: null,
        executedAmount: null,
        orderPrice: null,
        orderQuantity: null,
        optionType: null,
        covered: null,
        orderId: null,
        orderTime: null,
        tradingMarket: null,
        contractNumber: null,
        stampDutyRate: null,
        brokerageFee: null,
        regulatoryFee: null,
        settlementFee: null,
        transferFee: null,
        transactionTransferFee: null,
        exerciseTransferFee: null,
        transactionLevy: null,
        commission: null,
        settlementAmount: null,
        profitGroup: null,
        deliveryMonth: null,
        clearFlag: null,
        leverageQuantity: null,
        otherPlFee: null,
        otherPlDescription: null,
        reserveFund: null,
        clearGroupNumber: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSettlementDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加成交记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTradeRecord(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改成交记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTradeRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTradeRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除成交记录编号为"' + ids + '"的数据项？').then(function() {
        return delTradeRecord(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('trade/tradeRecord/export', {
        ...this.queryParams
      }, `tradeRecord_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "成交记录导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('trade/tradeRecord/importTemplate', {
      }, `trade_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 分配清算组编号按钮操作 */
    handleAssignClearGroup() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条记录");
        return;
      }

      this.$modal.confirm('确定要为选中的 ' + this.ids.length + ' 条记录分配清算组编号吗？')
        .then(() => {
          assignClearGroup(this.ids).then(response => {
            this.$modal.msgSuccess("分配成功");
            this.getList();
          }).catch(error => {
            this.$modal.msgError(error.msg || "分配失败");
          });
        })
        .catch(() => {});
    },
    /** 清除清算组编号按钮操作 */
    handleClearGroupNumber() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条记录");
        return;
      }

      this.$modal.confirm('确定要清除选中的 ' + this.ids.length + ' 条记录的清算组编号吗？')
        .then(() => {
          clearGroupNumber(this.ids).then(response => {
            this.$modal.msgSuccess("清除成功");
            this.getList();
          }).catch(error => {
            this.$modal.msgError(error.msg || "清除失败");
          });
        })
        .catch(() => {});
    },
    // 新增：检查列是否可见
    isColumnVisible(prop) {
      return this.selectedColumns.includes(prop);
    }
  }
}
</script>

<style scoped>
/* 添加样式使下拉框与工具栏对齐 */
/*.column-selector {*/
/*  display: inline-block;*/
/*  vertical-align: middle;*/
/*  margin-left: 10px;*/
/*}*/
/*.mb8 {*/
/*  display: flex;*/
/*  align-items: center;*/
/*  flex-wrap: wrap;*/
/*  gap: 15px;*/
/*  padding: 12px 15px;*/
/*  background: white;*/
/*  border-radius: 8px;*/
/*  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);*/
/*}*/
.column-selector-wrapper {
  display: flex;
  align-items: center;
  /*background: #f5f7fa;*/
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}
.column-selector-wrapper:hover {
  border-color: #c0c4cc;
}
.column-selector-wrapper:focus-within {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
.column-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
  margin-right: 10px;
}
.column-label i {
  margin-right: 4px;
  color: #409EFF;
}
@media (max-width: 768px) {
  .mb8 {
    flex-direction: column;
    align-items: flex-start;
  }
  .column-selector-wrapper {
    width: 100%;
  }
}
</style>
